package client

import (
	. "google.golang.org/grpc"
	"google.golang.org/grpc/connectivity"
	"log"
	"sync"
)

type ConnectPool struct {
	pool sync.Pool
}

func CreatePool(target string, opts ...DialOption) *ConnectPool {
	return &ConnectPool{
		pool: sync.Pool{
			New: func() any {
				conn, err := Dial(target, opts...)
				if err != nil {
					log.Fatalln(err)
				}
				return conn
			},
		},
	}
}

func (c *ConnectPool) Get() *ClientConn {
	//log.Printf("从连接池中获取conn:%+v\n",c.pool)
	conn := c.pool.Get().(*ClientConn)
	if conn.GetState() == connectivity.Shutdown || conn.GetState() == connectivity.TransientFailure {
		conn.Close()
		conn = c.pool.New().(*ClientConn)
	}

	return conn
}

func (c *ConnectPool) Put(conn *ClientConn) {
	//log.Printf("将conn放入连接池:%+v\n",c.pool)
	if conn.GetState() == connectivity.Shutdown || conn.GetState() == connectivity.TransientFailure {
		conn.Close()
		return
	}
	c.pool.Put(conn)
}
